<template>
    <div class="min-h-screen bg-gray-50 font-sans text-dark">
        <!-- 顶部导航栏 -->
        <el-header class="bg-white shadow-sm">
            <div
                class="container mx-auto px-4 h-full flex items-center justify-between"
            >
                <div class="flex items-center space-x-2">
                    <i class="fa fa-building-o text-primary text-2xl"></i>
                    <h1 class="text-xl font-semibold">智能资料校核列表</h1>
                </div>
            </div>
        </el-header>

        <!-- 主内容区 -->
        <main class="container mx-auto px-4 pt-5">
            <!-- 数据统计卡片 -->
            <el-row :gutter="16" class="mb-6">
                <el-col :xs="12" :md="6">
                    <el-card
                        class="h-full transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
                    >
                        <div class="flex items-center">
                            <div
                                class="w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-4"
                            >
                                <el-icon color="#165DFF" size="30">
                                    <List
                                /></el-icon>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">待审核项目</p>
                                <p class="text-2xl font-bold text-dark">
                                    {{ stats.pending }}
                                </p>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :xs="12" :md="6">
                    <el-card
                        class="h-full transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
                    >
                        <div class="flex items-center">
                            <div
                                class="w-12 h-12 rounded-full bg-success/10 flex items-center justify-center text-success mr-4"
                            >
                                <el-icon color="#52C41A" size="30">
                                    <Check
                                /></el-icon>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">已完成项目</p>
                                <p class="text-2xl font-bold text-dark">
                                    {{ stats.completed }}
                                </p>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :xs="12" :md="6">
                    <el-card
                        class="h-full transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
                    >
                        <div class="flex items-center">
                            <div
                                class="w-12 h-12 rounded-full bg-warning/10 flex items-center justify-center text-warning mr-4"
                            >
                                <el-icon color="#FAAD14" size="30">
                                    <WarnTriangleFilled
                                /></el-icon>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">异常项目</p>
                                <p class="text-2xl font-bold text-dark">
                                    {{ stats.abnormal }}
                                </p>
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :xs="12" :md="6">
                    <el-card
                        class="h-full transition-all duration-300 hover:shadow-lg hover:-translate-y-1"
                    >
                        <div class="flex items-center">
                            <div
                                class="w-12 h-12 rounded-full bg-[#F1EAFA]/100 flex items-center justify-center text-tax mr-4"
                            >
                                <el-icon color="#7E46D2" size="30"
                                    ><Money
                                /></el-icon>
                            </div>
                            <div>
                                <p class="text-sm text-gray-500">增值税结算</p>
                                <p class="text-2xl font-bold text-dark">
                                    {{ stats.taxSettlement }}
                                </p>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
            <!-- 批量操作按钮 -->
            <el-card class="mb-6">
                <!-- 页面标题和操作区 -->
                <div
                    class="flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-6"
                >
                    <div class="flex flex-wrap gap-3" style="width: 100%">
                        <el-input
                            v-model="searchInput"
                            placeholder="搜索项目编号/名称"
                            :prefix-icon="Search"
                            style="width: 300px"
                        />
                        <el-button
                            type="default"
                            :icon="Search"
                            class="flex items-center"
                            @click="handleSearch"
                        >
                            筛选
                        </el-button>
                        <el-button
                            type="default"
                            icon="Upload"
                            class="flex items-center"
                        >
                            导出
                        </el-button>
                    </div>
                </div>
                <!-- 批量操作按钮：删除原「批量删除/报价文件上传/分部分项查看」，新增「资料组卷/校验报告」 -->
                <div class="flex flex-wrap items-center gap-3">
                    <span class="text-sm text-gray-500"
                        >选中
                        <span class="font-medium text-primary">{{
                            selectedCount
                        }}</span>
                        项：</span
                    >

                    <el-button
                        type="success"
                        icon="Check"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="handleBatchSubmit"
                    >
                        批量提交
                    </el-button>
                    <el-button
                        type="primary"
                        icon="RefreshLeft"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="handleBatchRetrieve"
                    >
                        批量取回
                    </el-button>
                    <!-- 新增：资料组卷按钮 -->
                    <el-button
                        type="info"
                        icon="Files"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="openFileVolumeModal"
                    >
                        资料组卷
                    </el-button>
                    <!-- 新增：校验报告按钮 -->
                    <el-button
                        type="warning"
                        icon="Files"
                        size="small"
                        :disabled="selectedCount === 0"
                        @click="openVerificationReportModal"
                    >
                        校验报告
                    </el-button>
                </div>
            </el-card>

            <!-- 结算信息表格 -->
            <el-card class="mb-8">
                <div
                    class="p-4 border-b border-gray-100 flex justify-between items-center"
                >
                    <h3 class="text-lg font-semibold">结算项目列表</h3>
                    <div class="text-sm text-gray-500">
                        共
                        <span class="font-medium text-dark">{{
                            filteredProjects.length
                        }}</span>
                        条记录
                    </div>
                </div>

                <el-table
                    :data="paginatedProjects"
                    border
                    stripe
                    :header-cell-style="{ backgroundColor: '#F5F7FA' }"
                    class="w-full"
                    @selection-change="handleSelectionChange"
                    row-key="id"
                >
                    <el-table-column
                        type="selection"
                        width="55"
                        :reserve-selection="true"
                    />

                    <el-table-column
                        prop="projectNumber"
                        label="项目编号"
                        sortable
                    />

                    <el-table-column
                        prop="projectName"
                        label="项目名称"
                        sortable
                    >
                        <template #default="scope">
                            <div
                                @dblclick="handleProjectDblClick(scope.row)"
                                onselectstart="return false"
                                style="cursor: pointer"
                            >
                                {{ scope.row.projectName }}
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="projectType"
                        label="项目类型"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden md:table-cell"
                    />

                    <el-table-column
                        prop="constructionUnit"
                        label="建设单位"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden sm:table-cell"
                    />

                    <el-table-column
                        prop="supervisionUnit"
                        label="监理单位"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden lg:table-cell"
                    />

                    <el-table-column
                        prop="contractor"
                        label="承包商"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden xl:table-cell"
                    />
                    <el-table-column
                        prop="priceCompilation"
                        label="编制价"
                        sortable
                        :show-overflow-tooltip="true"
                        class="hidden xl:table-cell"
                    />

                    <el-table-column prop="taxSettlement" label="增值税结算">
                        <template #default="scope">
                            <el-tag
                                :type="
                                    scope.row.taxSettlement === '是'
                                        ? 'info'
                                        : 'default'
                                "
                                effect="light"
                            >
                                {{
                                    scope.row.taxSettlement === "是"
                                        ? "单独结算"
                                        : "合并结算"
                                }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop="status" label="状态">
                        <template #default="scope">
                            <el-tag
                                :type="getStatusType(scope.row.status)"
                                effect="light"
                            >
                                {{ scope.row.status }}
                            </el-tag>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 分页 -->
                <div class="mt-4">
                    <el-pagination
                        @size-change="handlePageSizeChange"
                        @current-change="handleCurrentPageChange"
                        :current-page="currentPage"
                        :page-sizes="[10, 20, 50]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="filteredProjects.length"
                    />
                </div>
            </el-card>
        </main>

        <!-- 页脚 -->
        <el-footer
            class="bg-white border-t border-gray-200 container mx-auto text-center text-gray-500 text-sm"
            style="height: 60px; line-height: 60px"
        >
            © 2023 智能资料校核列表 版权所有
        </el-footer>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, toRefs, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();
// 状态管理
const state = reactive({
    // 项目数据
    projects: [],
    // 搜索和分页
    searchInput: "",
    currentPage: 1,
    pageSize: 10,
    // 选中的项目ID集合
    selectedIds: new Set(),
    // 统计数据
    stats: {
        pending: 12,
        completed: 36,
        abnormal: 3,
        taxSettlement: 28,
    },
    // 模态框状态：删除原「showSectionModal/showUploadModal」，新增「资料组卷/校验报告」模态框
    showFileVolumeModal: false, // 新增：资料组卷模态框
    showVerificationReportModal: false, // 新增：校验报告模态框
    modalTitle: "",
    // 当前操作的项目：删除原「currentSectionProject/currentUploadProject」，新增「资料组卷/校验报告」项目
    currentProject: null,
    currentFileVolumeProject: null, // 新增：当前组卷项目
    currentVerificationProject: null, // 新增：当前校验项目
    // 文件上传相关：保留项目单独上传，新增组卷文件
    uploadFiles: [],
    volumeFiles: {
        // 新增：组卷文件分类存储
        basis: [], // 结算依据文件
        result: [], // 结算成果文件
    },
    // 新增：资料组卷标签页
    activeVolumeTab: "basis",
    // 新增：校验报告数据
    verificationReport: {
        checkDate: "",
        checker: "",
        checkType: "自动+人工复核",
        details: [
            {
                item: "项目信息完整性",
                standard: "项目编号、名称、建设单位等必填项完整",
                result: "通过",
                desc: "所有必填信息已填写",
            },
            {
                item: "结算价格逻辑性",
                standard: "审核价≤编制价，无负数价格",
                result: "通过",
                desc: "造价中心审核价12320000 ≤ 编制价12568900，逻辑正确",
            },
            {
                item: "增值税结算合规性",
                standard: "单独结算需提供增值税专用发票",
                result: "通过",
                desc: "已标记单独结算，发票文件已上传",
            },
            {
                item: "资料完整性",
                standard: "需包含合同、图纸等基础资料",
                result: "通过",
                desc: "基础资料已组卷完成",
            },
        ],
        issues: [],
        conclusion:
            "经校验，该项目结算数据完整、逻辑正确，符合《建设工程工程量清单计价规范》（GB 50500-2013）要求，可进入下一步审核流程。",
    },
    // 新增：校验状态
    verificationStatus: {
        type: "success",
        text: "校验通过",
    },
    // 表单数据
    formData: {
        id: null,
        projectNumber: "",
        projectName: "",
        projectType: "",
        constructionUnit: "",
        supervisionUnit: "",
        auditor: "",
        contractor: "",
        priceCompilation: null,
        taxSettlement: "是",
        preparedPrice: null,
        supervisionPrice: null,
        constructionPrice: null,
        costPrice: null,
        status: "待提交",
    },
    // 表单验证规则
    formRules: {
        projectNumber: [
            { required: true, message: "请输入项目编号", trigger: "blur" },
        ],
        projectName: [
            { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        projectType: [
            { required: true, message: "请选择项目类型", trigger: "change" },
        ],
        constructionUnit: [
            { required: true, message: "请输入建设单位", trigger: "blur" },
        ],
        taxSettlement: [
            {
                required: true,
                message: "请选择是否单独结算增值税",
                trigger: "change",
            },
        ],
        preparedPrice: [
            { required: true, message: "请输入结算编制价", trigger: "blur" },
            { type: "number", message: "请输入有效的数字", trigger: "blur" },
        ],
    },
    // 其他
    activeMenu: "settlement",
});

// 解构响应式状态
const {
    projects,
    searchInput,
    currentPage,
    pageSize,
    selectedIds,
    stats,
    activeMenu,
} = toRefs(state);

// 初始化项目数据
onMounted(() => {
    // 模拟API请求获取项目数据
    projects.value = [
        {
            id: 1,
            projectNumber: "XM-2023-0568",
            projectName: "城南新区道路拓宽改造工程",
            projectType: "市政基础设施",
            constructionUnit: "市城市建设投资集团",
            supervisionUnit: "恒信工程监理",
            contractor: "宏业建筑工程",
            priceCompilation: 1300000,
            preparedPrice: 12568900,
            costPrice: 12320000,
            taxSettlement: "是",
            status: "已完成",
        },
        {
            id: 2,
            projectNumber: "XM-2023-0572",
            projectName: "滨江公园景观提升工程",
            projectType: "园林绿化",
            constructionUnit: "市园林绿化管理处",
            supervisionUnit: "景程监理公司",
            contractor: "绿源景观工程",
            priceCompilation: 1400000,
            preparedPrice: 8750000,
            costPrice: 8620500,
            taxSettlement: "否",
            status: "审核中",
        },
        {
            id: 3,
            projectNumber: "XM-2023-0589",
            projectName: "城东污水处理厂扩建工程",
            projectType: "市政公用设施",
            constructionUnit: "市水务集团",
            supervisionUnit: "华信工程监理",
            contractor: "东方建设工程",
            priceCompilation: 12837722,
            preparedPrice: 25680000,
            costPrice: null,
            taxSettlement: "是",
            status: "待提交",
        },
        {
            id: 4,
            projectNumber: "XM-2023-0601",
            projectName: "老旧小区改造工程（一期）",
            projectType: "房建工程",
            constructionUnit: "市住房保障中心",
            supervisionUnit: "诚信监理公司",
            contractor: "惠民建筑工程",
            preparedPrice: 18950000,
            priceCompilation: 5434321,
            costPrice: 18560300,
            taxSettlement: "否",
            status: "待提交",
        },
        {
            id: 5,
            projectNumber: "XM-2023-0615",
            projectName: "城市供水管道改造工程",
            projectType: "市政管线",
            constructionUnit: "市自来水公司",
            supervisionUnit: "永安工程监理",
            contractor: "管道工程公司",
            priceCompilation: 542432431,
            preparedPrice: 9870000,
            costPrice: 9650000,
            taxSettlement: "是",
            status: "审核中",
        },
    ];
});

// 过滤项目数据
const filteredProjects = computed(() => {
    if (!searchInput.value) return projects.value;
    const searchStr = searchInput.value.toLowerCase();
    return projects.value.filter(
        (project) =>
            project.projectNumber.toLowerCase().includes(searchStr) ||
            project.projectName.toLowerCase().includes(searchStr)
    );
});

// 分页处理
const paginatedProjects = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    return filteredProjects.value.slice(
        startIndex,
        startIndex + pageSize.value
    );
});

// 选中数量计算
const selectedCount = computed(() => {
    return filteredProjects.value.filter((project) =>
        selectedIds.value.has(project.id)
    ).length;
});

// 根据状态获取标签类型
const getStatusType = (status) => {
    switch (status) {
        case "已完成":
            return "success";
        case "审核中":
            return "warning";
        case "待提交":
            return "info";
        default:
            return "default";
    }
};

// 处理选择变化
const handleSelectionChange = (selection) => {
    selectedIds.value.clear();
    selection.forEach((item) => {
        selectedIds.value.add(item.id);
    });
};

// 分页事件
const handlePageSizeChange = (size) => {
    pageSize.value = size;
    currentPage.value = 1;
};

const handleCurrentPageChange = (page) => {
    currentPage.value = page;
};

// 处理搜索
const handleSearch = () => {
    currentPage.value = 1;
    selectedIds.value.clear();
};

// 监听搜索输入变化
watch(searchInput, (newVal, oldVal) => {
    if (newVal !== oldVal) {
        selectedIds.value.clear();
    }
});

// 批量提交（保留原功能）
const handleBatchSubmit = () => {
    ElMessageBox.confirm(
        `确定要提交选中的${selectedCount.value}个项目进行审核吗？`,
        "确认批量提交",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "info",
        }
    )
        .then(() => {
            projects.value.forEach((p) => {
                if (selectedIds.value.has(p.id)) {
                    p.status = "审核中";
                }
            });
            selectedIds.value.clear();
            ElMessage.success("选中项目已提交审核");
        })
        .catch(() => {});
};

// 批量取回（保留原功能）
const handleBatchRetrieve = () => {
    ElMessageBox.confirm(
        `确定要取回选中的${selectedCount.value}个项目吗？`,
        "确认批量取回",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "info",
        }
    )
        .then(() => {
            projects.value.forEach((p) => {
                if (selectedIds.value.has(p.id)) {
                    p.status = "待提交";
                }
            });
            selectedIds.value.clear();
            ElMessage.success("选中项目已取回");
        })
        .catch(() => {});
};

// ---------------------- 新增：资料组卷功能 ----------------------
// 打开资料组卷模态框
const openFileVolumeModal = () => {
    router.push("/settMgmt/docCompilation");
};

// ---------------------- 新增：校验报告功能 ----------------------
// 打开校验报告模态框
const openVerificationReportModal = () => {
    router.push("/settMgmt/vrReports");
};
// 打开校验报告模态框
const handleProjectDblClick = (proj) => {
    console.log("proj", proj);

    router.push("/settMgmt/spdDetails");
};
</script>

<style scoped>
/* 统一颜色变量 */
:deep(.text-primary) {
    color: #165dff !important;
}
:deep(.text-upload) {
    color: #409eff !important;
}
:deep(.text-tax) {
    color: #7e46d2 !important;
}

/* 优化卡片 hover 效果 */
:deep(.el-card) {
    border: none !important;
    border-radius: 8px !important;
}

/* 优化分页样式 */
:deep(.el-pagination) {
    display: flex;
    justify-content: center;
}

/* 优化上传组件样式 */
:deep(.el-upload--drag) {
    border: 2px dashed #dcdfe6 !important;
    border-radius: 6px !important;
}
:deep(.el-upload--drag:hover) {
    border-color: #409eff !important;
}

/* 优化表格样式 */
:deep(.el-table__header th) {
    font-weight: 500 !important;
}
:deep(.el-table__body tr:hover > td) {
    background-color: #f9fafb !important;
}

/* 优化按钮样式 */
:deep(.el-button) {
    border-radius: 4px !important;
}
</style>
